# 从文本中找到用户的错误次数
import re
import os
current_dir = os.getcwd()
# 构建文件的绝对路径
file_path = os.path.join(current_dir,"函数与引用","完整功能的ATM登录", "登录状态.txt")
def findLine(str,strPre):
    pattern = re.compile(rf"{re.escape(strPre)}:(\d*)", re.IGNORECASE)
    res = pattern.search(str)
    if res==None:
        return 0
    else:
        return int(res.group(1))

# 读取某人的错误次数
def getErrorCount(user_name):
    with open(file_path, "r", encoding="utf-8", errors='ignore') as f:
        data = f.read()
        if user_name in data:
            return findLine(data,user_name)
        else:
            return 0
        
# 在文件后添加内容
def append(str):
    with open(file_path, "a", encoding="utf-8") as f: 
       f.write(f"\n{str}")

# 清空文件并写入新内容
def reset(str):
    with open(file_path, "w", encoding="utf-8") as f: 
       f.write(str)
# 更新错误次数
def updateErrorCount(user_name,num):
    with open(file_path, "r", encoding="utf-8", errors='ignore') as f:
        data = f.read()
        pattern = re.compile(rf"{re.escape(user_name)}:\d*", re.IGNORECASE)
        res = pattern.search(data)
        if res==None:
            # 未找到，在后面添加
            append(f"{user_name}:{num}")
        else:
            # 找到，更新
            newData = data.replace(res.group(),f"{user_name}:{num}")
            reset(newData)

# 判断是否存在
def userExist(name):
    return name in ["mm","tt","pp"]
# 模拟取钱并支持锁定
def bankLogin():
    user = [["mm","123"],["tt","456"],["pp","789"]]
    count = 0
    while count<9:
        user_name = input("请输入用户名：").strip()
        if not userExist(user_name):
            print("用户不存在，请重新输入用户名")
            continue
        pass_word = input("请输入密码：").strip()
        errCount = getErrorCount(user_name)
        if errCount >= 3:
            print("你的账号已被锁定，请重新输入用户名")
        else:
            for i,v in enumerate(user):
                if v[0]==user_name:
                    if v[1]==pass_word:
                        print("登录成功")
                        exit()
                    else:
                        print(f"密码错误，请重新输入密码，您还有{2-errCount}次机会")
                        updateErrorCount(user_name,errCount+1)
                        break
        count += 1
bankLogin()
            
    
